package cn.geminis.auth.server.service.loginHandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * @author puddi
 */
@Slf4j
@Service
@AllArgsConstructor
public class JsonSuccessHandler implements AuthenticationSuccessHandler {

    private final ObjectMapper objectMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        var result = new HashMap<String, Object>(8);
        result.put("code", 0);
        result.put("message", "登录成功");
        result.put("data", authentication);
        response.setContentType("application/json;charset=utf-8");
        var out = response.getWriter();
        out.write(objectMapper.writeValueAsString(result));
        out.flush();

        MDC.put("username", authentication.getPrincipal().toString());
        log.info("认证成功");
    }
}
